package spring.my.db.sharding.demo.controller.student;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import spring.my.db.sharding.demo.dto.StudentPageReqDTO;
import spring.my.db.sharding.demo.dto.StudentReqDTO;
import spring.my.db.sharding.demo.dto.StudentResDTO;
import spring.my.db.sharding.demo.exception.BzException;
import spring.my.db.sharding.demo.response.CommonPageResponse;
import spring.my.db.sharding.demo.response.CommonResponse;
import spring.my.db.sharding.demo.service.StudentService;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    private static final Logger log = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<List<StudentResDTO>> list(@RequestBody StudentReqDTO dto) {
        List<StudentResDTO> list = studentService.list(dto);
        return CommonResponse.getInstance(list);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<Boolean> add(@RequestBody StudentReqDTO dto) throws BzException {
        dto.setId(null);
        return CommonResponse.getInstance(studentService.save(dto));
    }

    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    public CommonResponse<Boolean> update(@PathVariable("id") Long id, @RequestBody StudentReqDTO dto) throws BzException {
        dto.setId(id);
        return CommonResponse.getInstance(studentService.save(dto));
    }

    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    @ResponseBody
    public CommonResponse<StudentResDTO> update(@PathVariable("id") Long id) {

        return CommonResponse.getInstance(studentService.detail(id));
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ResponseBody
    public CommonPageResponse<StudentResDTO> page(@RequestBody StudentPageReqDTO dto) {
        log.info(">>>> " + LocalDate.now());
        return CommonPageResponse.getInstance(studentService.page(dto));
    }

}
